package com.ougy.customcomponent;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

@SuppressLint("NewApi")
public class CustomScrollView extends ScrollView {
	public CustomScrollView(Context context) {
		super(context);
	}

	public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	private GestureDetector mGestureDetector;
	View.OnTouchListener mGestureListener;

	private ScrollViewListener scrollViewListener = null;

	public void setScrollViewListener(ScrollViewListener scrollViewListener) {
		this.scrollViewListener = scrollViewListener;
	}

	public CustomScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mGestureDetector = new GestureDetector(context, new YScrollDetector());
		setFadingEdgeLength(0);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return super.onInterceptTouchEvent(ev)
				&& mGestureDetector.onTouchEvent(ev);
	}

	@Override
	protected void onScrollChanged(int x, int y, int oldx, int oldy) {

		// if (isReadyForPullEnd()) { // if diff is zero, then the bottom has
		// been reached

		if (scrollViewListener != null) {
			if (isReadyForPullEnd()) {
				scrollViewListener.onScrollEnded(this, x, y, oldx, oldy);
			}
			if (isReadyForPullStart()) {
				scrollViewListener.onScrollStarted(this, x, y, oldx, oldy);
			}

		}

		super.onScrollChanged(x, y, oldx, oldy);
	}

	private boolean isReadyForPullStart() {
		return getScrollY() == 0;
	}

	private boolean isReadyForPullEnd() {
		View view = (View) getChildAt(getChildCount() - 1);
		int diff = (view.getBottom() - (getHeight() + getScrollY()));
		if (diff == 0)
			return true;
		else
			return false;
	}

	// Return false if we're scrolling in the x direction
	class YScrollDetector extends SimpleOnGestureListener {
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			if (Math.abs(distanceY) > Math.abs(distanceX)) {
				return true;
			}
			return false;
		}
	}

	public interface ScrollViewListener {
		void onScrollEnded(CustomScrollView scrollView, int x, int y, int oldx,
				int oldy);

		void onScrollStarted(CustomScrollView scrollView, int x, int y,
				int oldx, int oldy);
	}
}